package com.cedifie.lendapp.ui.steps.impl

import android.content.Context
import com.cedifie.lendapp.MyApplication
import com.cedifie.lendapp.R
import com.cedifie.lendapp.config.CedConfigs
import com.cedifie.lendapp.http.ApiService
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.http.IHttpCallback
import com.cedifie.lendapp.mvp.presenter.MvpPresenter
import com.cedifie.lendapp.ui.steps.view.ICedStepView
import com.cedifie.lendapp.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/14 13:58
 * @Annotation：流程步骤 Presenter 实现层
 */
class CedStepPresenterImpl(context: Context?) : MvpPresenter<ICedStepView>(context) {

    //流程步骤数据
    private var stepData: JSONObject? = null

    /**
     * 获取全部流程
     */
    fun loadCedProcessStepAction(){
        val stepString = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_PROCESS)
        if (stepString.isEmpty()){
            return
        }
        stepData = JSONObject(stepString)
        stepData?.let {
            val allStepTitles = it.optJSONArray("allStepTitles")
            val tabList = arrayListOf<JSONObject>()
            //当前进行的步骤
            val curtIndex = getStepIndex()
            allStepTitles?.let { allTitles ->
                for (i in 0 until allTitles.length()) {
                    val tabObj = JSONObject()
                    tabObj.put("tabTitle", allTitles.optString(i))
                    tabObj.put("selectIndex", curtIndex)
                    tabObj.put("isSelect", i == curtIndex)
                    tabList.add(tabObj)
                }
            }
            //设置所有步骤列表
            mvpView?.showCedProcessStepList(tabList,curtIndex)
            showCedStepPage()
        }
    }

    /**
     * 提交数据
     */
    fun onSubmitProcessAction(params: JSONObject){
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        val httpUrl = ApiService.getHttpUrl(ApiService.API_URL.CED_API_USER_URL)
        HttpHelper.postCedAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        mvpView?.showCedSubmitSuccess()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 根据Step类型显示不同的Page
     */
    private fun showCedStepPage(){
        //当前进行的步骤
        val curtIndex = getStepIndex()
        stepData?.let { data ->
            val allSteps = data.optJSONArray("allSteps")
            if (curtIndex == -1){//所有步骤已完成
                mvpView?.showCedLoanAppalyPage()
                return
            }
            //获取对应的key
            val curtKey = allSteps?.optString(curtIndex)
            //Contact 类型
            if (data.has(curtKey)){
                val stepData = data.optJSONObject(curtKey)
                stepData?.put("stepTitle",curtKey)
                if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                    mvpView?.showCedStepContactPage(stepData)
                    return
                }
            }

            curtKey?.let { key ->
                //todo Ocr证件照样式
                if (key.contains("ocr_info")){
                    mvpView?.showCedStepOcrPage()
                    return
                }

                //todo Selfie自拍照样式
                if (key.contains("sefie_info")){
                    mvpView?.showCedStepSelfiePage()
                    return
                }

                //todo Account账户样式（法语地区绑定账号）
                if (key.contains("account_info") && CedConfigs.isFrench()){
                    mvpView?.showCedStepAccountPage()
                    return
                }
                //常规通用样式
                if (data.has(key)){
                    val stepData = data.optJSONObject(key)
                    stepData?.put("stepTitle",key)
                    mvpView?.showCedStepCommonPage(stepData)
                }
            }
        }
    }

    /**
     * 获取 steps 中第一个在步骤在总步骤中是第几个
     */
    private fun getStepIndex(): Int{
        var index = -1
        //剩余未完成步骤
        val steps = stepData?.optJSONArray("steps")
        if (steps == null || steps.length() == 0){//已完成
            return index
        }
        //总步骤
        val allSteps = stepData?.optJSONArray("allSteps") ?: return index

        //当前进行的步骤
        val curtStep = steps.optString(0)
        for (i in 0..<allSteps.length()){
            if (curtStep == allSteps.optString(i)){
                index = i
                break
            }
        }
        return index
    }
}